<?php
include_once("Service.php"); 
class ServiceEnum extends Service
{
  /**
   *select by parent's id
   *@param pid parent's id
   *@return the result(encode)
   */
  public function getByPid($pid)
  {
    $sql = $pid==-1?"select streid,strname from tbenum where strpid=?":"select streid,strpid,strname,strvalue from tbenum where strpid=?";
    $res = (new dbHelper())->getRecords($sql,array($pid),PDO::FETCH_ASSOC);
    //直接使用json_encode对于ajax请求来说，会有乱码问题，这里需要进行转码
    //以下转码方法只对utf8编码文字有效,非utf8编码字符，请参考urlencode(iconv('gb2312','utf-8',$val['name']));
    /*
    for($i=0;$i<count($res);$i++)
    {
      foreach($res[$i] as $key => $value)
      $res[$i][$key]=urlencode($value);
    }
    */
    echo json_encode($res);
    unset($res);
  }
  
  /**
   *select by id
   *@param pid parent's id
   *@return the result(encode)
   */
  public function getById($id)
  {
    throw new Exception("not complement");
  }
  
  //create
  /**
   *add a new record 
   *@param $arrParams 
   */
  public function create($arrParams)
  {
    try
    {
      $sql = "insert into tbenum(strpid,strname,strvalue,streid) values(?,?,?,?)";
      $db = new dbHelper();
      //get the maxid
      $maxid = $db->getRecord("select case count(streid) when 0 then 10001 else max(convert(streid,signed))+1 end from tbenum");
      array_push($arrParams,$maxid[0]);
      $res = (new dbHelper())->insertRecord($sql,$arrParams);
      return $this->msgFunc(array("status"=>"suc","code"=>1,"msg"=>"添加成功","streid"=>$maxid[0],"strpid"=>$arrParams[0],"strname"=>$arrParams[1],"strvalue"=>$arrParams[2]));
    }
    catch(PDOException $ex)
    {
      //handle exception
      throw $ex;
      //return the errmsg
      return $this->msgFunc(array("status"=>"err","code"=>-1,"msg"=>"服务端出错了"));
    }
    finally
    {
      unset($db);
    }
  }
  /**
   *Delete a record
   */
  public function delete($strpid,$streid)
  {
    try
    {
      $res = (new dbHelper())->delRecord("delete from tbenum where strpid= ? and streid= ?",array($strpid,$streid));
      return json_encode(array("status"=>"suc","msg"=>$res));
    }
    catch(PDOException $ex)
    {
      //handle the exception

      //return the error message
      return json_encode(array("status"=>"err","msg"=>"删除失败"));
    }
    finally
    {
      
    }
  }
  /**
   *update a record by id and pid
   *@param $arrParams the array of parameters
   */
  public function update($arrParams)
  {
    try
    {
      $res = (new dbHelper())->updateRecord("update tbenum set strname = ?,strvalue= ? where strpid= ? and streid= ?",$arrParams);
      return json_encode(array("status"=>"suc","msg"=>$res,"strname"=>$arrParams[0],"strvalue"=>$arrParams[1]));
    }
    catch(PDOException $ex)
    {
      //handle the exception

      //return the error message
      return json_encode(array("status"=>"err","msg"=>"删除失败"));
    }
    finally
    {
      
    }
  }
}
 ?>